package com.example.finalproject.collection;

import com.example.finalproject.car.Car;
import com.example.finalproject.car.CarService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Controller
public class CollectionController {
    //自动注入对象
    @Autowired
    private CarService carService;
    @Autowired
    private CollectionService collectionService;
    //初始化需要用到的收藏列表 和 car列表
    public static List<Collection> collectionList = new ArrayList<Collection>();
    public static List<Car> carList = new ArrayList<Car>();
    //详情页点击《添加收藏》，传入carId调用car包里的接口查找相关汽车信息
    @RequestMapping("/addCollection")
    public String addCollection(String carId, Model model){
        collectionList = collectionService.findAllCollection();
        for(int i = 0;i < collectionList.size(); i++){
            if(!collectionList.get(i).getCarId().equals(carId)){
                //不存在这个carId
                continue;
            }
            //存在这个carId
            System.out.println("车已存在，添加收藏失败");
            model.addAttribute("error_Details","这个车已经在你的收藏里了！！！");
            return "index";
        }
        //需要清空列表，重新从数据库查询获取
        carList.clear();
        collectionList.clear();
        //将这个carId添加到数据库收藏表
        collectionService.insertCollection(carId);
        //获取收藏表中的所有收藏汽车id添加到列表
        collectionList = collectionService.findAllCollection();
        //遍历收藏列表，获取列表中每个id对应的汽车信息添加到car列表中
        for(int i = 0;i<collectionList.size(); ++i){
            String temporary_carId = collectionList.get(i).getCarId();
            Car temporary_car = carService.selectCarById(temporary_carId);
            carList.add(temporary_car);
        }
        model.addAttribute("carList", carList);
        System.out.println("添加收藏成功");
        return "collection";
    }
    //取消收藏
    @RequestMapping("/cancel_Collection")
    public String cancel_Collection(String carId,Model model){
        //需要清空列表，重新从数据库查询获取
        carList.clear();
        collectionList.clear();
        //删除对应汽车
        collectionService.deleteCarById(carId);
        //获取收藏表中的所有收藏汽车id添加到列表
        collectionList = collectionService.findAllCollection();
        //遍历收藏列表，获取列表中每个id对应的汽车信息添加到car列表中
        for(int i = 0;i<collectionList.size(); ++i){
            String temporary_carId = collectionList.get(i).getCarId();
            Car temporary_car = carService.selectCarById(temporary_carId);
            carList.add(temporary_car);
        }
        model.addAttribute("carList",carList);
        System.out.println("取消"+carId+"号车收藏成功");
        return "collection";
    }
    //查询所有汽车
    @RequestMapping("/findAllCollection")
    public List<Collection> findAll(){
        return collectionService.findAllCollection();
    }
}
